/*
 * Copyright 2020 Matt Jamesson <scifidryer@gmail.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package modbusmechanic.gateway;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import modbusmechanic.ModbusMechanic;
/**
 *
 * @author Matt Jamesson <scifidryer@gmail.com>
 */
public class GatewayFrame extends javax.swing.JFrame {

    GatewayManager manager = null;
    /**
     * Creates new form GatewayFrame
     */
    public GatewayFrame() {
        initComponents();
        manager = new GatewayManager(this);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel6 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        tcpPortField = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jPanel7 = new javax.swing.JPanel();
        jLabel14 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel12 = new javax.swing.JLabel();
        comPortSelector = new javax.swing.JComboBox<>();
        jLabel13 = new javax.swing.JLabel();
        baudRateSelector = new javax.swing.JComboBox<>();
        jLabel15 = new javax.swing.JLabel();
        dataBitsField = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        stopBitsField = new javax.swing.JTextField();
        jPanel5 = new javax.swing.JPanel();
        jLabel17 = new javax.swing.JLabel();
        paritySelector = new javax.swing.JComboBox<>();
        remoteMonitoringCheckbox = new javax.swing.JCheckBox();
        jSeparator2 = new javax.swing.JSeparator();
        jPanel9 = new javax.swing.JPanel();
        gatewayMonitorCheckbox = new javax.swing.JCheckBox();
        monitorPane = new javax.swing.JPanel();
        monitorPane.setVisible(false);
        jPanel8 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        gatewayMonitorTextArea = new javax.swing.JTextArea();
        jPanel10 = new javax.swing.JPanel();
        clearHistoryButton = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JSeparator();
        jPanel1 = new javax.swing.JPanel();
        statusLabel = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        startStopButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("TCP Slave -> RTU Master Gateway");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel2.setText("Modbus TCP Slave Settings");
        jPanel6.add(jLabel2);

        getContentPane().add(jPanel6);

        jLabel1.setText("TCP Port");
        jPanel4.add(jLabel1);

        tcpPortField.setColumns(4);
        tcpPortField.setText("502");
        jPanel4.add(tcpPortField);

        getContentPane().add(jPanel4);
        getContentPane().add(jSeparator1);

        jLabel14.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel14.setText("RTU Master Serial settings");
        jPanel7.add(jLabel14);

        getContentPane().add(jPanel7);

        jLabel12.setText("Port");
        jPanel2.add(jLabel12);

        comPortSelector.setModel(new DefaultComboBoxModel(ModbusMechanic.getPortNames()));
        comPortSelector.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comPortSelectorActionPerformed(evt);
            }
        });
        jPanel2.add(comPortSelector);

        jLabel13.setText("Baud");
        jPanel2.add(jLabel13);

        baudRateSelector.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "4800", "9600", "14400", "19200", "38400", "57600" }));
        jPanel2.add(baudRateSelector);

        jLabel15.setText("Data bits");
        jPanel2.add(jLabel15);

        dataBitsField.setColumns(2);
        dataBitsField.setText("8");
        jPanel2.add(dataBitsField);

        jLabel16.setText("Stop bits");
        jPanel2.add(jLabel16);

        stopBitsField.setColumns(2);
        stopBitsField.setText("1");
        jPanel2.add(stopBitsField);

        getContentPane().add(jPanel2);

        jLabel17.setText("Parity");
        jPanel5.add(jLabel17);

        paritySelector.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "None", "Odd", "Even", "Mark", "Space" }));
        paritySelector.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                paritySelectorActionPerformed(evt);
            }
        });
        jPanel5.add(paritySelector);

        remoteMonitoringCheckbox.setText("Allow remote telnet monitoring");
        jPanel5.add(remoteMonitoringCheckbox);

        getContentPane().add(jPanel5);
        getContentPane().add(jSeparator2);

        gatewayMonitorCheckbox.setText("Show gateway monitor");
        gatewayMonitorCheckbox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                gatewayMonitorCheckboxActionPerformed(evt);
            }
        });
        jPanel9.add(gatewayMonitorCheckbox);

        getContentPane().add(jPanel9);

        monitorPane.setLayout(new javax.swing.BoxLayout(monitorPane, javax.swing.BoxLayout.Y_AXIS));

        gatewayMonitorTextArea.setEditable(false);
        gatewayMonitorTextArea.setColumns(50);
        gatewayMonitorTextArea.setRows(5);
        jScrollPane1.setViewportView(gatewayMonitorTextArea);

        jPanel8.add(jScrollPane1);

        monitorPane.add(jPanel8);

        clearHistoryButton.setText("Clear History");
        clearHistoryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearHistoryButtonActionPerformed(evt);
            }
        });
        jPanel10.add(clearHistoryButton);

        monitorPane.add(jPanel10);

        getContentPane().add(monitorPane);
        getContentPane().add(jSeparator3);

        statusLabel.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        statusLabel.setForeground(new java.awt.Color(255, 0, 0));
        statusLabel.setText("Gateway is stopped");
        jPanel1.add(statusLabel);

        getContentPane().add(jPanel1);

        startStopButton.setText("Start Gateway");
        startStopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startStopButtonActionPerformed(evt);
            }
        });
        jPanel3.add(startStopButton);

        saveButton.setText("Save Gateway Settings");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });
        jPanel3.add(saveButton);

        getContentPane().add(jPanel3);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void comPortSelectorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comPortSelectorActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_comPortSelectorActionPerformed

    private void paritySelectorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_paritySelectorActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_paritySelectorActionPerformed

    private void startStopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startStopButtonActionPerformed
        manager.handleStartStop();
        
    }//GEN-LAST:event_startStopButtonActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        manager.stopGateway();
    }//GEN-LAST:event_formWindowClosing

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("CFG file", "cfg");
        chooser.setFileFilter(filter);
        int status = chooser.showSaveDialog(this);
        if (status == JFileChooser.APPROVE_OPTION)
        {
            java.io.File f = chooser.getSelectedFile();
            String filename = f.getName();
            if (!filename.substring(filename.length()-4).equalsIgnoreCase(".cfg"))
            {
                f = new File(f.getParent() + File.separator + f.getName() + ".cfg");
            }
            saveProperties(f);
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void gatewayMonitorCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gatewayMonitorCheckboxActionPerformed
        monitorPane.setVisible(gatewayMonitorCheckbox.isSelected());
        pack();
    }//GEN-LAST:event_gatewayMonitorCheckboxActionPerformed

    private void clearHistoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearHistoryButtonActionPerformed
        gatewayMonitorTextArea.setText("");
    }//GEN-LAST:event_clearHistoryButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GatewayFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GatewayFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GatewayFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GatewayFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GatewayFrame().setVisible(true);
            }
        });
    }
    public void saveProperties(java.io.File f)
    {
        Properties prop = new Properties();
        prop.put("tcpport", tcpPortField.getText());
        prop.put("comport", comPortSelector.getSelectedItem().toString());
        prop.put("baud", baudRateSelector.getSelectedItem().toString());
        prop.put("databits", dataBitsField.getText());
        prop.put("stopbits", stopBitsField.getText());
        prop.put("parity", paritySelector.getSelectedIndex() + "");
        String allowMonitor = "0";
        if (remoteMonitoringCheckbox.isSelected())
        {
            allowMonitor = "1";
        }
        prop.put("allowmonitor", allowMonitor);
        try
        {
            FileOutputStream fos = new FileOutputStream(f);
            prop.store(fos, "");
            fos.close();
        }
        catch (Exception e)
        {
            if (ModbusMechanic.debug)
            {
                e.printStackTrace();
            }
            JOptionPane.showMessageDialog(this, e.getMessage(), "Save Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JComboBox<String> baudRateSelector;
    private javax.swing.JButton clearHistoryButton;
    public javax.swing.JComboBox<String> comPortSelector;
    public javax.swing.JTextField dataBitsField;
    public javax.swing.JCheckBox gatewayMonitorCheckbox;
    public javax.swing.JTextArea gatewayMonitorTextArea;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JPanel monitorPane;
    public javax.swing.JComboBox<String> paritySelector;
    public javax.swing.JCheckBox remoteMonitoringCheckbox;
    private javax.swing.JButton saveButton;
    public javax.swing.JButton startStopButton;
    public javax.swing.JLabel statusLabel;
    public javax.swing.JTextField stopBitsField;
    public javax.swing.JTextField tcpPortField;
    // End of variables declaration//GEN-END:variables
}
